package cn.edu.hitsz.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import org.apache.log4j.Category;

import populus.core.queue.UrlItem;

/**
 * THE HTTPREQUEST CLASS FOR SEND REQUEST TO SERVER URL ----JAVA.NET.URL
 * HTTPMETHOD ----BUILD CLASS (HTTP METHODS FOR REQUEST A SERVER [GET POS ])
 * FETCHOPTION ----BUILD CLASS(PERSONAL FETCH OPTIONS)
 * 
 * @author mingchen
 * @date 2015年8月10日
 */
public class HTTPRequest {
	public final Category LogClass = Category.getInstance(HTTPRequest.class);

	private final UrlItem url;
	private HTTPMethod method;
	private FetchOption option;

	/**
	 * 
	 * Constructor function of Class
	 * 
	 * @param url
	 * 
	 * @param method
	 * 
	 * @param option
	 */
	public HTTPRequest(UrlItem url) {

		this.url = url;
	}

	public HTTPRequest(UrlItem url, HTTPMethod method) {

		this.url = url;
		this.method = method;
	}

	public HTTPRequest(UrlItem url, HTTPMethod method, FetchOption option) {

		this.url = url;
		this.method = method;
		this.option = option;

	}

	/**
	 * @return the url java.net.URL
	 */
	public UrlItem getUrl() {
		return url;
	}

	/**
	 * @return the method HTTPRequest method
	 */
	public HTTPMethod getMethod() {
		return method;
	}

	/**
	 * @return the option FetchOption
	 */
	public FetchOption getOption() {
		return option;
	}

	/**
	 * 
	 * @param url
	 *            URL
	 * @param method
	 *            HTTPMethod
	 * @param option
	 *            FetchOption void 2015年8月11日
	 */
	public HTTPResponse GET() {
		BufferedReader in = null;
		String content = "";
		URL readUrl = null;
		try{
			readUrl = new URL(url.getUrl());
			URLConnection connection = readUrl.openConnection();
			setRequestProperty(connection);
			connection.connect();
			LogClass.info("Connect to server:" + readUrl);
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line = in.readLine();
			while (line != null) {
				content += line;
				line = in.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		HTTPResponse response = new HTTPResponse(readUrl, content);
		return response;
	}

	/**
	 * Set the request property here
	 * 
	 * @param connection
	 *            void 2015年8月11日
	 */
	private void setRequestProperty(URLConnection conn) {
		if (conn == null) {
			throw new IllegalArgumentException("The connection cannot be null");
		}
		conn.setRequestProperty("User-Agent",
				"Mozilla/5.0(windows 7 home)Firefox/3.0.3");
		conn.setRequestProperty("Accept-Language", "en-us,en;q=0.7,zh-cn;q=0.3");
		conn.setRequestProperty("Accept-Encoding", "utf-8");
		conn.setRequestProperty("Accept-Charset",
				"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
		conn.setRequestProperty("Keep-Alive", "300");
		conn.setRequestProperty("connnection", "keep-alive");
		conn.setRequestProperty("If-Modified-Since",
				"Fri, 02 Jan 2009 17:00:05 GMT");
		conn.setRequestProperty("If-None-Match", "\"1261d8-4290-df64d224\"");
		conn.setRequestProperty("Cache-conntrol", "max-age=0");

	}

	/**
	 * 
	 * @param url
	 *            URL
	 * @param option
	 *            FetchOption
	 * @return String
	 * 
	 * 
	 *         2015年8月11日
	 */
	public HTTPResponse POST() {
		String content = "";
		PrintWriter out = null;
		BufferedReader in = null;
		URL readUrl = null;
		try {
			readUrl = new URL(url.getUrl());
			URLConnection connection = readUrl.openConnection();
			setRequestProperty(connection);
			connection.setDoOutput(true);
			connection.setDoInput(true);
			// Set the parameters for post request
			out = new PrintWriter(connection.getOutputStream());
			out.print(option.getParaAsString());
			out.flush();
			// read the content of the response
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				content += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		HTTPResponse response = new HTTPResponse(readUrl, content);
		return response;
	}

	/**
	 * Add parameters to the url
	 * 
	 * @param url
	 * @param para
	 * @return String 2015年8月11日
	 */
	public String fixURL(URL url, Map<String, Object> para) {
		String realUrl = url.toString() + "?";
		for (String key : para.keySet()) {
			realUrl += key + "=" + para.get(key).toString() +"&";
		}
		realUrl.substring(0, realUrl.length() - 1);
		return realUrl;
	}
}
